package com.lxu.report.service;

import com.lxu.report.entity.WordEntity;
import com.lxu.report.entity.bo.ReportDirBO;
import com.lxu.report.entity.bo.ReportTableBO;
import com.lxu.report.util.ReportToolsConstant;
import com.lxu.report.util.XWPFUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 模板数据填充接口
 */
@Service
public class WordTemplateFillService {

    @Autowired
    private MultipleRowsCopyService multipleRowsCopyService;

    /**
     * 扩展表格+填充数据
     *
     * @param dir
     * @param templateTextMap
     * @param templateTables
     * @throws Exception
     */
    public void fill(ReportDirBO dir, Map<String, Object> templateTextMap, List<ReportTableBO> templateTables) throws Exception {

        XWPFUtils.save(dir.getDestFilePath(), new XWPFDocument(new FileInputStream(new File(dir.getTemplateFilePath()))));

        for (ReportTableBO templateTable : templateTables) {
            /**
             * 多行复制
             */
            if (templateTable.isMultipleFormFlag()) {
                extendTable4ComplexForm(templateTable, dir);
            }
        }

        /**
         * 2、填充表单数据（占位符填充）
         */
        InputStream in = new FileInputStream(new File(dir.getDestFilePath()));
        WordEntity wordEntity = new WordEntity();
        wordEntity.setTextMap(templateTextMap);
        fillPlaceholder(wordEntity, in, dir.getDestFilePath());

        /**
         * 3、扩展表格+填充表格数据
         */
        for (ReportTableBO templateTable : templateTables) {
            if(!templateTable.isMultipleFormFlag()){
                /**
                 * 单行复制
                 */
                /**
                 * 1.1、扩展表格行数
                 */
                extendTable(templateTable, dir);

                /**
                 * 1.2、填充表格扩展行数据(单行表格扩展)
                 */
                fillTable(templateTable, dir);
            }
        }
    }

    /**
     * 表格中多行同时复制场景
     *
     * @param templateTable
     * @param dir
     * @throws Exception
     */
    private void extendTable4ComplexForm(ReportTableBO templateTable, ReportDirBO dir) throws Exception {
        InputStream in = new FileInputStream(new File(dir.getDestFilePath()));
        XWPFDocument xwpfDocument = new XWPFDocument(in);
        XWPFTable table = XWPFUtils.getTableByIndex(xwpfDocument, templateTable.getExportConfigEntity().getTableIndex());
        int startRow = templateTable.getExportConfigEntity().getStartPosition();
        int extendRows = templateTable.getRecordCount();
        int copyRows = templateTable.getExportConfigEntity().getMinRows();
        for (int i = 1; i < extendRows; i++) {
            for (int j = startRow; j < startRow + copyRows; j++) {
                multipleRowsCopyService.copy(table, j, j + copyRows, i);
            }
        }
        XWPFUtils.save(dir.getDestFilePath(), xwpfDocument);
    }

    /**
     * 扩展表格行
     *
     * @param templateTable
     * @param dir
     * @throws Exception
     */
    private void extendTable(ReportTableBO templateTable, ReportDirBO dir) throws Exception {
        InputStream in2 = new FileInputStream(new File(dir.getDestFilePath()));
        WordEntity wordEntity2 = new WordEntity();
        wordEntity2.setTableMap(templateTable.getTemplateTables());
        wordEntity2.setStartRow(templateTable.getExportConfigEntity().getStartPosition());
        for (Map.Entry entry : templateTable.getTemplateTables().entrySet()) {
            wordEntity2.setRows(((List<List<String>>) entry.getValue()).size());
            String key = (String) entry.getKey();
            wordEntity2.setTableIndex(Integer.parseInt(key.substring(key.indexOf(ReportToolsConstant.TABLE_PREFIX) + ReportToolsConstant.TABLE_PREFIX.length(), key.length())));
        }
        extendTableRows(wordEntity2, in2, dir.getDestFilePath());
    }

    /**
     * 填充表格行数据
     *
     * @param templateTable
     * @param dir
     * @throws Exception
     */
    private void fillTable(ReportTableBO templateTable, ReportDirBO dir) throws Exception {
        InputStream in3 = new FileInputStream(new File(dir.getDestFilePath()));
        WordEntity wordEntity3 = new WordEntity();
        wordEntity3.setTableMap(templateTable.getTemplateTables());
        for (Map.Entry entry : templateTable.getTemplateTables().entrySet()) {
            wordEntity3.setRows(((List<List<String>>) entry.getValue()).size());
        }
        wordEntity3.setStartRow(templateTable.getExportConfigEntity().getStartPosition());
        fillTableData(wordEntity3, in3, dir.getDestFilePath());
    }

    /**
     * 填充占位符
     *
     * @param wordEntity
     * @throws Exception
     */
    public void fillPlaceholder(WordEntity wordEntity, InputStream in, String fileName) throws Exception {
        XWPFDocument xwpfDocument = XWPFUtils.fillComplexWord(in, wordEntity);
        XWPFUtils.save(fileName, xwpfDocument);
    }

    /**
     * @param wordEntity
     * @param in
     * @throws Exception
     */
    public void extendTableRows(WordEntity wordEntity, InputStream in, String fileName) throws Exception {
        XWPFDocument xwpfDocument = new XWPFDocument(in);
        XWPFTable table = XWPFUtils.getTableByIndex(xwpfDocument, wordEntity.getTableIndex());
        XWPFUtils.insertRows(table, wordEntity.getStartRow(), wordEntity.getRows() - ReportToolsConstant.INIT_TABLE_ROWS);
        XWPFUtils.save(fileName, xwpfDocument);
    }

    /**
     * 填充表格数据
     *
     * @param wordEntity
     * @param in
     * @throws Exception
     */
    public void fillTableData(WordEntity wordEntity, InputStream in, String fileName) throws Exception {
        XWPFDocument xwpfDocument = XWPFUtils.fillComplexWord(in, wordEntity);
        XWPFUtils.save(fileName, xwpfDocument);
    }
}